package cn.com.dashihui.web.base;

import java.io.IOException;

import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.core.Controller;
import com.jfinal.kit.JsonKit;
import com.jfinal.upload.UploadFile;

import cn.com.dashihui.kit.CommonKit;
import cn.com.dashihui.kit.FTPClientKit;
import cn.com.dashihui.web.dao.Admin;
import cn.com.dashihui.web.domain.AjaxResult;

public class BaseController extends Controller{
	protected Logger logger = LoggerFactory.getLogger(getClass());
	/**
	 * 获取当前登录用户
	 */
	public Admin getCurrentUser(){
		return (Admin)SecurityUtils.getSubject().getPrincipal();
	}
	
	/**
	 * 上传图片至指定FTP目录，并返回重新生成的UUID文件名（含扩展名部分，可直接保存数据库）
	 */
	protected String uploadToFtp(String ftpPath,UploadFile file) throws IOException{
		//获取文件，并上传至FTP根目录下，用UUID重命名
		String fileName = file.getFileName();
		String extension = fileName.substring(fileName.lastIndexOf("."));
		String newFileName = CommonKit.getUUID();
		FTPClientKit.upload(ftpPath, newFileName + extension, file.getFile());
		return newFileName + extension;
	}
	
	protected void deleteFromFtp(String ftpPath,String fileName) throws IOException{
		FTPClientKit.deleteFile(ftpPath + fileName);
	}
	
	protected void deleteFromFtp(String filePath) throws IOException{
		FTPClientKit.deleteFile(filePath);
	}
	
	/**
	 * 返回json格式内容
	 */
	public void renderResult(int flag){
		this.renderText(JsonKit.toJson(new AjaxResult(flag)));
	}
	
	public void renderResult(int flag,String message){
		this.renderText(JsonKit.toJson(new AjaxResult(flag,message)));
	}
	
	public void renderResult(int flag,String message,Object object){
		this.renderText(JsonKit.toJson(new AjaxResult(flag,message,object)));
	}
	
	public void renderResult(int flag,Object object){
		this.renderText(JsonKit.toJson(new AjaxResult(flag,object)));
	}
	
	public void renderSuccess(){
		renderResult(AjaxResult.FLAG_SUCCESS);
	}
	
	public void renderSuccess(String message){
		renderResult(AjaxResult.FLAG_SUCCESS,message);
	}
	
	public void renderSuccess(Object object){
		renderResult(AjaxResult.FLAG_SUCCESS,object);
	}
	
	public void renderSuccess(String message,Object object){
		renderResult(AjaxResult.FLAG_SUCCESS,message,object);
	}
	
	public void renderFailed(){
		renderResult(AjaxResult.FLAG_FAILED);
	}
	
	public void renderFailed(String message){
		renderResult(AjaxResult.FLAG_FAILED,message);
	}
}
